package com.gsc.runner;

import com.gsc.constants.SystemConstants;
import com.gsc.domain.entity.Article;
import com.gsc.mapper.ArticleMapper;
import com.gsc.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author gscstart
 * @create 2023/2/15-14:38
 * 实现CommandLineRunner接口，程序启动时执行。注入到bean容器中
 */
@Component
public class ViewCountRunner implements CommandLineRunner {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private RedisCache redisCache;


    @Override
    public void run(String... args) throws Exception {
        //查询博客信息，id、viewCount
        List<Article> articles = articleMapper.selectList(null);
            //使用stream流转成map  ViewCount是Long类型 不能自增，所以转成Integer
        Map<String, Integer> viewCountMap = articles.stream()
                .collect(Collectors.toMap(article1 -> article1.getId().toString(), article -> article.getViewCount().intValue()));
        //将id，viewCount作为key和values存储到redis中
        redisCache.setCacheMap(SystemConstants.REDIS_VIEW_COUNT,viewCountMap);
        System.out.println("成功存入redis");
        //项目启动时，将博客的浏览量存储到redis中

    }
}
